import { storagePrefix, storageExpireTime } from "../config/site"

export default class MyStorage {
  constructor(key = '',) {
    this.key = storagePrefix + key;
  }

  valGetValidate(key) {
    const valObj = JSON.parse(wx.getStorageSync(key) || '{}');
    const storageEffectTime = valObj.time * 1 + 1000 * 60 * 60 * valObj.expireTime;
    const isValidate = storageEffectTime > + new Date();
    return [isValidate, valObj];
  }

  get(defaultVal = '') {
    const [isValidate, valObj] = this.valGetValidate(this.key);
    if (!isValidate || !valObj.result) {
      if (valObj.result) {
        wx.removeStorageSync(this.key);
      }
      return defaultVal;
    }
    return valObj.result;
  }

  set(newVal, expireTime = storageExpireTime) {
    wx.setStorageSync(this.key, JSON.stringify({
      time: +new Date(),
      expireTime,
      result: newVal,
    }));
  }

  updateAll() {
    const myStorageReg = new RegExp(`^${this.key}`)
    const res = wx.getStorageInfoSync();
    const keys = res.keys.filter(item => myStorageReg.test(item));
    keys.map(item => {
      this.update(item);
    });
  }

  update(key) {
    let [isValidate, valObj] = this.valGetValidate(key);
    if (isValidate) {
      valObj = Object.assign({}, valObj, { time: +new Date() });
    }
    wx.setStorageSync(key, JSON.stringify(valObj));
  }

}